package vitamin.demo.config;
import org.springframework.data.redis.core.RedisTemplate;
import vitamin.demo.certification.diyexception.MisRequestException;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author HAC
 */
@WebFilter(urlPatterns = {"/*"})
public class LoginFilter implements Filter {

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //校验用户登录状态
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //Filter过滤器跨域处理
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);//允许域名请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许请求的方式
        response.setHeader("Access-Control-Max-Age", "1800");//指定本次预检请求的有效期，单位为秒
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token");//自定义请求头，放置token
        response.setHeader("Access-Control-Allow-Credentials", "true");//页面中允许显示请求头

        //获取请求中的token
        String token=request.getHeader("token");
        token = token==null ? "" : token;

        //查询token在Redis中的剩余时间
        Long expire = redisTemplate.getExpire(token);

        if(expire > 0){ //是登录状态

            redisTemplate.expire(token,60L, TimeUnit.MINUTES);//重置token的时间，保持登录信息有效

            filterChain.doFilter(servletRequest,servletResponse);//允许请求
        }else {//登录状态失效
            response.sendRedirect("/index.html");
        }
    }

    @Override
    public void destroy() {

    }
}
